<template>
    <section>
        <div v-if="state.image.length" class="relative">
            <my-image fit="cover" :src="props.modelValue" class="w-[150px] h-[150px]" />
            <div class="absolute right-[-10px] top-[-10px] bg-white w-[25px] h-[25px] rounded-[10px]"
                @click="deleteImage(props.hash)">
                <el-icon :size="20" color="red">
                    <i-ep-CircleClose />
                </el-icon>
            </div>
        </div>
        <el-upload v-else ref="uploadRef" v-model:file-list="state.image" list-type="picture-card" :limit="1"
            :http-request="submitUpload">
            <el-icon>
                <i-ep-Plus />
            </el-icon>
        </el-upload>
    </section>
</template>

<script lang='ts' setup>
import { UploadInstance, UploadRequestOptions } from "element-plus";

type Props = {
    modelValue: string,
    hash: string,
};

const props = withDefaults(defineProps<Props>(), {
    modelValue: undefined
});
const emit = defineEmits([
    "update:modelValue",
    "update:hash",
]);

const state = reactive({
    image: []
})

const initData = () => {
    if (props.modelValue) {
        state.image = [props.modelValue] as any
    }
}

initData()

const uploadRef = ref<UploadInstance>()

const submitUpload = async (fileObj: UploadRequestOptions) => {
    Utils.Modal().loading('上传中~')
    const file = fileObj.file;

    const [compressErr, compress] = await Utils.ImageCompressToRatio(file, 0.6)
    if (compressErr) return

    const [base64Err, base64] = await Utils.FileToBase64(compress)
    if (base64Err) return Utils.Modal().alert('图片解析错误~')

    const str = base64.split('base64,')[1]
    const [err, res] = await CommonService.uploadImage({ base64: str })
    Utils.Modal().closeLoading()
    if (err) return Utils.Modal().msgError(err)
    const { url, hash } = res?.data || {}
    state.image = [url] as any
    emit("update:modelValue", url);
    emit("update:hash", hash);
}

const deleteImage = async (hash: string) => {
    Utils.Modal().loading('上传中~')
    const [err, res] = await CommonService.deleteImage({ hash })
    Utils.Modal().closeLoading()
    // if (err) return Utils.Modal().msgError(err)
    if (err) console.log('CommonService.deleteImage :>> ', err)
    state.image = []
    emit("update:modelValue", "");
    emit("update:hash", "");
}

</script>

<style lang='scss' scoped></style>